package com.joiant.community.provider;

import java.io.IOException;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.joiant.community.dto.AccessTokenDTO;
import com.joiant.community.dto.GiteeToken;
import com.joiant.community.dto.GiteeUser;

import okhttp3.*;


@Component
public class GiteeProvider {

	public String getAccessToken(AccessTokenDTO accessTokenDTO) {
		MediaType mediaType = MediaType.get("application/json; charset=utf-8");
		OkHttpClient client = new OkHttpClient();

		RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(accessTokenDTO));
		Request request = new Request.Builder()
				.url("https://gitee.com/oauth/token")
				.post(body)
				.build();
		try (Response response = client.newCall(request).execute()) {
			String string = response.body().string();
			GiteeToken giteeToken = JSON.parseObject(string, GiteeToken.class);
			return giteeToken.getAccess_token();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}
	
	public GiteeUser getUser(String accessToken) {
		OkHttpClient client = new OkHttpClient();
		Request request = new Request.Builder().url("https://gitee.com/api/v5/user?access_token=" + accessToken).build();
		
		try {
			Response response = client.newCall(request).execute();
			String string = response.body().string();
			GiteeUser giteeUser = JSON.parseObject(string,GiteeUser.class);
			return giteeUser;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
